<!-- 批量逆地址解析，获取后端传递的对象数组Locations，批量解析经纬度并展示到地图界面上 -->
<template>
  <div id="container"></div>
</template>

<script>
import { getHotels } from "../api/map";

export default {
  name: "mapPLJX",

  data() {
    return {
      userId: 1,//需要登陆界面获取
      addr: [],
      lng: 0.0,
      lat: 0.0,
      city: "",
    };
  },

  methods: {
    //批量解析地址信息并标记
    initializeMap() {
      var self = this; // 保存this
      //   console.log(self.lng);//访问成功
      var map = new BMapGL.Map("container");
      map.centerAndZoom(new BMapGL.Point(self.lng, self.lat), 13);
      map.enableScrollWheelZoom(true);
      var myGeo = new BMapGL.Geocoder();
      var adds = self.addr;
      //   console.log(adds);
      var index = 0;
      function bdGEO() {
        for (; index < adds.length; index++) {
          var add = adds[index];
          geocodeSearch(add);
        }
      }
      function geocodeSearch(add) {
        if (index < adds.length) {
          setTimeout(window.bdGEO, 400);
        }
        myGeo.getPoint(
          add,
          function(point) {
            if (point) {
              var address = new BMapGL.Point(point.lng, point.lat);
              addMarker(
                address,
                new BMapGL.Label(add, {
                  offset: new BMapGL.Size(10, -10),
                })
              );
            }
          },
          self.city // 使用保存的self变量
        );
      }
      // 编写自定义函数,创建标注
      function addMarker(point, label) {
        var marker = new BMapGL.Marker(point);
        map.addOverlay(marker);
        marker.setLabel(label);
      }
      bdGEO();
    },
    //初始化参数
    getParams(){
      //预留接口，用于接收userId
      //this.userId = sessionStorage.getItem("userId")
    }
  },

  mounted() {
    //初始化参数
    this.getParams();
    //获取用户所在城市酒店名列表
    getHotels(this.userId).then((res) => {
      this.addr = res.data;
      this.lng = res.map.userLng;
      this.lat = res.map.userLat;
      this.city = res.map.city;
      /*   console.log(res);
    //   console.log(this.addr);
    //   console.log(this.lng);
    //   console.log(this.lat);
    //   console.log(this.city);*/
      //执行地图初始化代码
      this.initializeMap();
    });
  },
};
</script>

<style>
#container {
  overflow: hidden;
  width: 100%;
  height: 100%;
  margin: 0;
  font-family: "微软雅黑";
}
</style>
